package untils

import (
	"bytes"
	"context"
	"encoding/json"
	"github.com/elastic/go-elasticsearch/v7/esapi"
	"log"
	"strconv"
	"sync"
	"user_srv/basic/config"
	"user_srv/handler/models"
)

func SyncToEs() {
	var wg sync.WaitGroup
	var c models.Car
	cartType, _ := c.CartType()

	for _, car := range cartType {
		wg.Add(1)

		go func(car *models.Car) {
			defer wg.Done()

			// Build the request body.
			data, err := json.Marshal(car)
			if err != nil {
				log.Fatalf("Error marshaling document: %s", err)
			}

			// Set up the request object.
			req := esapi.IndexRequest{
				Index:      "car",
				DocumentID: strconv.Itoa(int(car.Id)),
				Body:       bytes.NewReader(data),
				Refresh:    "true",
			}

			// Perform the request with the client.
			res, err := req.Do(context.Background(), config.Es)
			if err != nil {
				log.Fatalf("Error getting response: %s", err)
			}
			defer res.Body.Close()

		}(car)
	}
	wg.Wait()

}
